﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility;
using DoubleH.Utility.Configuration;
using System.Net;
using System.Net.Sockets;
using DoubleH.Utility.IO;
using Table=FCNS.Data.Table;
using System.Data;
using FSLib.IPMessager;
using System.Collections.ObjectModel;
using DHserver.Plugins;

namespace DHserver
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
            InitPlugin();
        }

        IPMClient lanClient = null;
        public ObservableCollection<StationStruct> allStation = new ObservableCollection<StationStruct>();
        bool closeMe = false;

        PluginManager pluginManager = new PluginManager();
        public PluginManager PluginManager { get { return pluginManager; } }

        /// <summary>
        /// 添加日志
        /// </summary>
        public void AddLog(string text)
        {
            listBoxLog.Items.Insert(0, text);
        }

        private void InitPlugin()
        {
            DefaultPluginHost pluginDefaultHost = new DefaultPluginHost();
            pluginDefaultHost.Initialize(this);
            pluginManager.Initialize(pluginDefaultHost);
            pluginManager.LoadAllExtension();

            dataGridExtExtension.ItemsSource = pluginManager.Plugins;
        }

        private void InitVar()
        {
            dataGridExtStation.ItemsSource = allStation;
            foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    comboBoxIp.Items.Add(ip.ToString());

            comboBoxIp.Text = DoubleHConfig.AppConfig.ServerIP;
            integerUpDownPort.Value = DoubleHConfig.AppConfig.ServerPort;
            checkBoxWeb.IsChecked = DoubleHConfig.AppConfig.UseBuilt_InWeb;
            //服务
            StartNet();
            StartWeb();

            InitUI(false);

            DoubleH.Utility.WindowsUtility.SetStartWithWindows(DoubleHConfig.AppConfig.AutoRunServer, FCNS.Data.DbDefine.baseDir + "DHserver.exe");
        }

        private void InitEvent()
        {
            显示MenuItem.Click += (ss, ee) => ShowNow();
            退出MenuItem.Click += (ss, ee) => CloseNow();
            comboBoxIp.SelectionChanged += (ss, ee) => ComboBoxIpSelectionChanged();
            this.Closing += (ss, ee) => CloseMe(ee);
            buttonJieZhuan.Click += (ss, ee) => JieZhuan();
            buttonLogin.Click += (ss, ee) => Login();
            buttonConfig.Click += (ss, ee) => ShowAppConfig();
            buttonSendMessage.Click += (ss, ee) => SendMessage();

            buttonClear.Click += (ss, ee) => Clear();
            buttonCouponsS.Click += (ss, ee) => ZuoFeiCouponsS();
            buttonCheckCorS.Click += (ss, ee) => CheckTable("CorS");
            buttonCheckProductS.Click += (ss, ee) => CheckTable("ProductS"); 
        }

        private void CheckTable(string tableName)
        {
            List<string> lt = new List<string>();
            StringBuilder sb = new StringBuilder();

            int i = 0;
            object obj = FCNS.Data.SQLdata.ExecuteScalar("select count(*) from " + tableName);
            int.TryParse(obj.ToString(), out i);
            foreach (DataRow row in FCNS.Data.SQLdata.GetDataRows("select Id,Code,Name from "+tableName))
            {
                string code = row["Code"] as string;
                if (!string.IsNullOrEmpty(code))
                    continue;

                    do
                    {
                        i += 1;
                        code = string.Format("{0:" + FCNS.Data.DbDefine.codeLenght + "}", i);
                    }
                    while (CodeIsExists(tableName, code));

                    sb.Append("update " + tableName + " set Code='" + code + "' where Id=" + row["Id"]);
                    sb.Append("\r\n");
                    System.IO.File.WriteAllText("c:\\q.txt", sb.ToString());
                    lt.Add("update " + tableName + " set Code='" + code + "' where Id=" + row["Id"]);
                    listBoxLog.Items.Insert(0, row["Name"].ToString() + " Code 修正为:" + code);
            }
            FCNS.Data.SQLdata.ExecuteNonQuery(lt.ToArray());
        }

        private bool CodeIsExists(string tableName, string code)
        {
            return FCNS.Data.SQLdata.ExecuteScalar("select Id from " + tableName + " where Code like '" + code + "'") != null;
        } 

        private void SendMessage()
        {
            if (string.IsNullOrEmpty(textBoxMessage.Text))
                return;

            List<FSLib.IPMessager.Entity.Host> host = new List<FSLib.IPMessager.Entity.Host>();
            foreach (object obj in dataGridExtStation.SelectedItems)
                host.Add(((StationStruct)obj).Host);

            if (host.Count == 0)
                MessageWindow.Show("请选择需要发送消息的站点");
            else
            {
                SendMessageToLan(textBoxMessage.Text, host.ToArray());
                MessageWindow.Show("发送成功");
            }

            textBoxMessage.Clear();
        }

        private void ComboBoxIpSelectionChanged()
        {
            StopNet();
            DoubleHConfig.AppConfig.ServerIP = comboBoxIp.SelectedItem.ToString();
            StartNet();
        }

        private void ShowAppConfig()
        {
            SysConfig.MainWindow mw = new SysConfig.MainWindow();
            mw.Init(null);
            mw.ShowDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bl">true 用户已登录,可以编辑控件内容.</param>
        private void InitUI(bool bl)
        {
            groupBox1.IsEnabled = bl;
            groupBox2.IsEnabled = bl;
            tabControl1.IsEnabled = bl;
            buttonLogin.IsEnabled = !bl;
            buttonConfig.IsEnabled = bl;
        }

        private void Login()
        {
            if (!DoubleH.Utility.Login.LoginUtility.ShowLoginWindowSuccess(Table.UserS.EnumFlag.操作员))
                return;
            if ( Table.UserS.LoginUser.UserNO != "root")
                return;

            InitUI(true);
            //结转,必须放在这里.因为只有登陆成功了才会访问数据库.才会更新结转的状态.
            dateTimePickerStart.Value = DateTime.Now;
            if (FCNS.Data.DbDefine.JieZhuan == null)
                return;

            labelTitle.Content = "上一个结转日:" + FCNS.Data.DbDefine.JieZhuan.Value;
            buttonJieZhuan.Content = "结转";
            switch (Table.SysConfig.SysConfigParams.JieZhuanMode)
            {
                case 2: dateTimePickerStart.IsEnabled = true; break;
                default: dateTimePickerStart.IsEnabled = false; break;
            }
        }

        private void JieZhuan()
        {
            if (dataGridExtStation.Items.Count > 1)
            {
                MessageWindow.Show("请上传POS端离线数据和关闭所有客户端连接再执行本操作.");
                return;
            }

            bool ok = true;
            if (FCNS.Data.DbDefine.JieZhuan != null)
            {
                switch (Table.SysConfig.SysConfigParams.JieZhuanMode)
                {
                    case 1:
                        DateTime tempDT=FCNS.Data.DbDefine.JieZhuan.Value.AddMonths(1);
                        int allDay=DateTime.DaysInMonth(tempDT.Year,tempDT.Month);
                        DateTime nextDT = new DateTime(tempDT.Year, tempDT.Month, (Table.SysConfig.SysConfigParams.JieZhuanRi > allDay ? allDay : (int)Table.SysConfig.SysConfigParams.JieZhuanRi));
                        if (dateTimePickerStart.Value.Value.Date < nextDT)
                        {
                            MessageWindow.Show("本期结转日为:" + nextDT);
                            ok = false;
                        }
                        break;

                    case 2:
                        //if (dateTimePickerStart.Value.Value < FCNS.Data.DbDefine.JieZhuan.Value.AddDays(Table.SysConfig.SysConfigParams.JieZhuanRi))
                        //{
                        //    MessageWindow.Show("本期结转日为:" + FCNS.Data.DbDefine.JieZhuan.Value.AddDays(Table.SysConfig.SysConfigParams.JieZhuanRi));
                        //    ok = false;
                        //}
                        break;

                    default:
                        {
                            MessageWindow.Show("系统未开启‘结转’功能");
                            ok = false;
                        }
                        break;
                }
            }
            if (ok)
            {
                if (MessageWindow.Show("", "确定要继续吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;

                Table.JieZhuanS js = new Table.JieZhuanS();
                js.OrderDateTime = dateTimePickerStart.Value.Value.Date;
                Table.DataTableS.EnumDatabaseStatus result = js.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                {
                    labelTitle.Content = "上一个结转日:" + FCNS.Data.DbDefine.JieZhuan.Value;
                    buttonJieZhuan.Content = "结转";
                }

                MessageWindow.Show(result.ToString());
            }
        }

        private void CloseMe(System.ComponentModel.CancelEventArgs ee)
        {
            if (!closeMe)
            {
                ee.Cancel = true;
                this.Visibility = Visibility.Hidden;
                this.ShowInTaskbar = false;
                return;
            }

            DoubleHConfig.AppConfig.ServerIP = comboBoxIp.Text;
            DoubleHConfig.AppConfig.ServerPort = integerUpDownPort.Value.Value;
            DoubleHConfig.AppConfig.UseBuilt_InWeb = checkBoxWeb.IsChecked.Value;
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);

            pluginManager.UnloadAllExtension();

            StopNet();
            StopWeb();
        }

        private void Clear()
        {
            if (buttonLogin.IsEnabled)
            {
                MessageWindow.Show("请先登录");
                return;
            }

            tabItemLog.IsSelected = true;
            buttonClear.IsEnabled = false;
            ClearUploadFile("GroupS");
            ClearUploadFile("ProductS");
            ClearUploadFile("WeiBaoS");
            ClearUploadFile("ItDbS");
            buttonClear.IsEnabled = true;
        }

        private void ClearUploadFile(string dirName)
        {
            listBoxLog.Items.Insert(0, "开始清理 Data\\"+dirName+" 目录");

            List<string> ok = new List<string>();
            foreach (DataRow row in FCNS.Data.SQLdata.GetDataRows("select UploadFile from "+dirName+" where UploadFile not like ''"))
                ok.Add(row[0] as string);

            foreach (string fi in Directory.GetFiles(FCNS.Data.DbDefine.MediaFileDirForClient + dirName))
                if (!ok.Contains(System.IO.Path.GetFileName(fi)))
                {
                    try { File.Delete(fi); }
                    catch { listBoxLog.Items.Insert(0, fi + " 无法删除"); }
                }

        }

        private void ExtensionConfig(object sender, RoutedEventArgs e)
        {
            if (dataGridExtExtension.SelectedCells.Count == 0)
                return;

            PluginInfo info = dataGridExtExtension.SelectedCells[0].Item as PluginInfo;
            if (info != null)
                info.Interface.ShowConfigWindow();
        }

        private void ZuoFeiCouponsS()
        {
            if (MessageWindow.Show("操作不可逆", "确定要作废 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 前的所有优惠券吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;

            Table.CouponsS ps = new Table.CouponsS();
            ps.ZuoFei(DateTime.Now);
            listBoxLog.Items.Insert(0, "优惠券作废成功.");
        }
        //private void StartFileTransfer()
        //{
        //    //内网共享式访问
        //    //FileTools ft = new FileTools();
        //    //if (ft.ShareFolder(FCNS.Data.DbDefine.dataDir, "doubleH$", "use for DHserver"))
        //    //{
        //    //    loadFileServer = true;
        //    //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/right_24.png"));
        //    //}
        //    //else
        //    //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));
        //    //远程访问
        //    //SocketServerManager.Init(DoubleHConfig.AppConfig.Server);
        //    //SocketServerManager.Start();
        //}


        //static Config.ClientConfig GetDefaultConfig()
        //{
        //    return new ClientConfig()
        //    {
        //        IPMClientConfig = new FSLib.IPMessager.Entity.Config
        //        {
        //            Port = 2425,
        //            GroupName = Environment.MachineName,
        //            NickName = Environment.UserName,
        //            ForceOldContract = true,
        //            IgnoreNoAddListFlag = false,
        //            EnableHostNotifyBroadcast = false,
        //            HostName = Environment.MachineName,
        //            AutoReplyWhenAbsence = true,
        //            AutoDetectVersion = true,
        //            BanedHost = new List<string>(),
        //            KeepedHostList = new List<string>(),
        //            BindedIP = IPAddress.Any,
        //            VersionInfo = "程序版本号: " ,
        //            AbsenceSuffix = " [离开]",
        //            Services = ServiceManager.GetServices(new string[] { "addins" }),
        //            EnableBPContinue = true,
        //            TaskKeepTime = 600,
        //            TasksMultiReceiveCount = 1
        //        },
        //        AbsenceMessage = new List<string>()
        //        {
        //            "我有事暂时不在，稍后联系你",
        //            "我吃饭去了！",
        //            "有事启奏 >_< 无事退朝",
        //            "还钱请电话，借钱请关机！"
        //        },

        //        HostGroupConfig = new SerializableDictionary<string, string>(),
        //    };
        //}

        //#region file transfer
        //private void StartFileTransfer()
        //{
        //    if (string.IsNullOrEmpty(comboBoxIp.Text))
        //        return;

        //    loadFileServer = true;
        //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/right_24.png"));


        //    //Control.CheckForIllegalCrossThreadCalls = false;
        //    D_ThreadRec _D_ThreadRec = new D_ThreadRec(ThreadRec);
        //    _D_ThreadRec.BeginInvoke(null, null);
        //}

        //private void StopFileTransfer()
        //{
        //    loadFileServer = false;
        //    if (serverSocket != null)
        //        serverSocket.Close();

        //    imageHost.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DHserver;component/Images/error_24.png"));
        //}

        ///// <summary>
        ///// 监听服务函数
        ///// </summary>
        //private void ThreadRec()
        //{
        //    try
        //    {
        //        IPAddress ip = IPAddress.Parse(DoubleHConfig.AppConfig.DefaultHost);
        //        IPEndPoint ipe = new IPEndPoint(ip, DoubleHConfig.AppConfig.DefaultHostPort);
        //        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //        serverSocket.Bind(ipe);
        //        serverSocket.Listen(10);
        //        ErrorS.WriteLogFile("服务器开始监听" + DoubleHConfig.AppConfig.DefaultHostPort + "端口！");
        //        while (true)
        //        {
        //            if (loadFileServer == true)
        //            {
        //                try
        //                {
        //                    //阻塞监听至到有新的连接
        //                    Socket temp = serverSocket.Accept();
        //                    IPEndPoint clientip = (IPEndPoint)temp.RemoteEndPoint;
        //                    //如果连接上
        //                    if (temp.Connected)
        //                    {
        //                        ServerReceiveFile startThreads = new ServerReceiveFile(temp);
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    if (ex.Message != "一个封锁操作被对 WSACancelBlockingCall 的调用中断。")//断开socket时阻塞监听的报错提示
        //                        MessageBox.Show(ex.Message);
        //                }
        //            }
        //            else
        //            {

        //                serverSocket.Close();
        //                ErrorS.WriteLogFile("停止监听服务！");
        //                break;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageWindow.Show(ex.Message);
        //        ErrorS.WriteLogFile(ex.Message);
        //    }
        //}
        //#endregion
    }
}